package org.bjf.modules.wechatpay.core;

import lombok.extern.slf4j.Slf4j;
import org.bjf.modules.wechatpay.constants.PayConstant;
import org.bjf.modules.wechatpay.query.WechatRequest;
import org.bjf.modules.wechatpay.util.PayUtil;
import org.bjf.utils.Http;

/**
 * 微信支付
 *
 * @author bjf
 * @see https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=8_1
 */
@Slf4j
public class WechatPay {

    private WechatPay() {
    }

    /**
     * 内部类实现单例安全
     */
    public static WechatPay getInstance() {
        return InnerClass.instance;
    }

    public <T> T execute(WechatRequest req, Class<T> clz) {
        //====1.签名
        String sign = PayUtil.sign(req, PayConstant.SECRETKEY);
        req.setSign(sign);
        //====2.转成request xml
        String requestXml = PayUtil.objectToXml(req);
        log.info("wechat pay request,name={},content={}", req.getClass().getSimpleName(), requestXml);
        String respXml = Http.postJson(req.getUrl(), requestXml).getBody();
        log.info("wechat pay response,name={},content={}", req.getClass().getSimpleName(), respXml);
        //===3、response xml转obj
        return PayUtil.xmlToObject(respXml, clz);
    }

    private static class InnerClass {

        private final static WechatPay instance = new WechatPay();
    }
}
